package com;

import javax.swing.*;
import com.trusfort.redis.DBIndex;
import com.trusfort.redis.JedisClient;
import com.trusfort.redis.RedisConnectionPool;
import com.util.FileUtils;
import com.util.Log;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.ScanResult;
import java.awt.*;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.awt.event.ActionEvent;

public class Main {
	private static JTextField txtHost;
	private static JTextField txtPort;
	private static long total = 0;
	private static JTextField txtSavePath;
	
	String[] redisKeys = { 
			"XDID::aimei", 
			"XDID::abmac", 
			"XDID::amac", 
			"XDID::aaid", 
			"XDID::abid", 
			"XDID::absn",
			"XDID::afpid",
			"XDID::afdid", 
			"XDID::asn", 
			"XDID::acid"
			};
	private static JTextArea txtLog;
	private static JTextField txtLimit;
	

	public static void logInfo(String msg) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String cur = sdf.format(new Date());

		System.out.println(msg);
		txtLog.append(msg+"\n");
		
		FileUtils.write(txtSavePath.getText() + "/logs/info.txt", cur + " [INFO] " + msg);
	}


	public void saveInvalidField(String fileName, String msg) {
		FileUtils.write(txtSavePath.getText() + "/" + fileName + ".txt", msg);
	}

	/**
	 * 统计每个特征key个数
	 */
	public void statFieldCount() {

		try {

			String ip = txtHost.getText();
			int port = Integer.valueOf(txtPort.getText());
			JedisClient client = new JedisClient(ip, port,null);

			logInfo("分析安卓特征值   Key 数量开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			
			for (String key : redisKeys) {
				logInfo("  分析安卓特征值  【" + key + "】 Key数量开始");
				
				total = 0;
				getScanResultCount(client, "0", key + "*");
				
				logInfo("  分析安卓特征值  【" + key + "】 Key数量结束，共" + total + "条");
			}
			
			logInfo("分析安卓特征值   Key 数量结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

		} catch (Exception e1) {
		  logInfo("Redis异常>>"+e1.fillInStackTrace());
		}
	}

	/**
	 * 统计无效字段
	 */
	public void statInvalidField() {

		try {

			String ip = txtHost.getText();
			int port = Integer.valueOf(txtPort.getText());
			JedisClient client = new JedisClient(ip, port,null);

			logInfo("分析安卓无效特征值对应设备指纹 数量开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			
			for (String key : redisKeys) {
				
				logInfo("  分析无效特征值  【" + key + "】 对应设备指纹数量开始>>");
				
				total = 0;
				getScanResult(client, "0", key + "*");
				
				logInfo("  分析无效特征值  【" + key + "】 对应设备指纹数量结束<<");
			}
			logInfo("分析安卓无效特征值对应设备指纹 数量结束");

		} catch (Exception e1) {
		  logInfo("Redis异常>>"+e1);
		}

	}

	public static void main(String[] args) {
		JFrame jf = new JFrame("Redis数据分析");
		jf.setSize(839, 481);
		jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		jf.setLocationRelativeTo(null);

		// 创建内容面板，指定使用 流式布局
		JPanel panel = new JPanel();
		panel.setLayout(null);
		JButton btn05 = new JButton("分析");
		btn05.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				new Thread(new Runnable() {//启动数据获取，更新显示进程 
 
                public void run() { 
                	Main main = new Main();

                	main.statInvalidField();
                } 
            }).start(); // 
			}
		});
		btn05.setBounds(717, 32, 69, 23);
		panel.add(btn05);

		jf.setContentPane(panel);

		txtHost = new JTextField();
		txtHost.setText("88.1.46.34");
		txtHost.setBounds(101, 33, 163, 21);
		panel.add(txtHost);
		txtHost.setColumns(10);

		JLabel lblIp = new JLabel("IP:");
		lblIp.setBounds(68, 36, 54, 15);
		panel.add(lblIp);

		JLabel label = new JLabel("端口：");
		label.setBounds(68, 69, 54, 15);
		panel.add(label);

		txtPort = new JTextField();
		txtPort.setText("6379");
		txtPort.setColumns(10);
		txtPort.setBounds(101, 66, 163, 21);
		panel.add(txtPort);

		JLabel label_1 = new JLabel("日志保存目录：");
		label_1.setBounds(288, 69, 96, 15);
		panel.add(label_1);

		txtSavePath = new JTextField();
		txtSavePath.setText("d:/test/");
		txtSavePath.setColumns(10);
		txtSavePath.setBounds(394, 66, 225, 21);
		panel.add(txtSavePath);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(86, 112, 700, 286);
		panel.add(scrollPane);
		
		txtLog = new JTextArea();
		txtLog.setLineWrap(true);
		scrollPane.setViewportView(txtLog);
		txtLog.setColumns(10);
		
		JLabel label_2 = new JLabel("条数大于等于：");
		label_2.setBounds(288, 36, 96, 15);
		panel.add(label_2);
		
		txtLimit = new JTextField();
		txtLimit.setText("10");
		txtLimit.setColumns(10);
		txtLimit.setBounds(394, 33, 99, 21);
		panel.add(txtLimit);
		jf.setVisible(true); // PS: 最后再设置为可显示(绘制), 所有添加的组件才会显示
	}

	public void getScanResult(JedisClient client, String cursor, String pattern) {
		try {

			ScanResult<String> result2 = client.scan(DBIndex.XDID_DB_INDEX, pattern, cursor, 10000);

			java.util.List<String> keys = new ArrayList();

			String fileName = pattern.replace("*","").split("::")[1];
			
			java.util.List<String> list = result2.getResult();
			if (list != null && !list.isEmpty()) {
				for (int j = 0; j < list.size(); j++) {
					keys.add(list.get(j));
				}
				scard(fileName, keys);
			}


			if (result2.getCursor() != 0) {
				getScanResult(client, String.valueOf(result2.getCursor()), pattern);
			}

		} catch (Exception e) {
		  logInfo("Redis异常>>"+e);
		}
	}

	public static void getScanResultCount(JedisClient client, String cursor, String pattern) {
		try {

			ScanResult<String> result2 = client.scan(DBIndex.XDID_DB_INDEX, pattern, cursor, 10000);

			java.util.List<String> list = result2.getResult();
			total += list.size();

			if (result2.getCursor() != 0) {
				getScanResultCount(client, String.valueOf(result2.getCursor()), pattern);
			}

		} catch (Exception e) {
		  logInfo("Redis异常>>"+e);
		  
		}
	}

	public void scard(String fileName, java.util.List<String> list) throws Exception {

		// 管道返回的结果集

		java.util.List<Map<String, Object>> searchResult = new ArrayList<Map<String, Object>>();

		Jedis jedis = null;
		try {
			jedis = RedisConnectionPool.getInstance().getJedis(DBIndex.XDID_DB_INDEX);

			Pipeline pipeline = jedis.pipelined();

			for (String key : list) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("key", key);
				map.put("response", pipeline.scard(key));
				searchResult.add(map);
			}
			pipeline.sync();

			if (searchResult.size() > 0) {
				for (Map<String, Object> keyResult : searchResult) {

					Response<Long> resp = (Response<Long>) keyResult.get("response");

					String key = keyResult.get("key").toString();
					if (resp.get() >= Integer.valueOf(txtLimit.getText())) {
					  saveInvalidField(fileName, "[" + key + "]对应设备指纹数" + resp.get());
					}
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
			RedisConnectionPool.getInstance().returnResource(jedis);
		}
	}
}